package com.youpai.platform.vulture.service.channel;


import com.youpai.platform.vulture.service.util.ChannelIdGeneratorUtil;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

/**
 * @date: 2022/7/8 23:34
 * @author: Anna
 * @version: 1.0
 * @description: channel属性值
 */
@Slf4j
@Data
@Accessors(chain = true)
public class ChannelAttrs {

    public static final AttributeKey<ChannelAttrs> VULTURE_ATTRS = AttributeKey.valueOf("VULTURE.ATTRS");

    /**
     * 客户端版本号
     */
    private String clientVersion;
    /**
     * vulture版本号
     */
    private String vultureVersion;
    /**
     * {@link com.youpai.platform.vulture.common.enums.IMTypeEnum}
     */
    private int channelType = -1;
    /**
     * appId
     */
    private int appId = -1;
    /**
     * 绑定通道的accId
     */
    private String accId;
    /**
     * 重复使用次数
     */
    private int reuseCount = 0;
    /**
     * 创建时间
     */
    private long createTime;
    /**
     * 最近一次生效时间
     */
    private long recentlyEffectiveTime;
    /**
     * channelId
     */
    private String channelId;
    /**
     * im类型
     */
    private int imType = -1;

    private ChannelAttrs(VultureChannel vultureChannel) {
        Channel channel = vultureChannel.getChannel();
        recentlyEffectiveTime = createTime = System.currentTimeMillis();
        channelId = ChannelIdGeneratorUtil.generateChannelId(channel);
    }

    public static ChannelAttrs getAttrs(VultureChannel vultureChannel) {
        Channel channel = vultureChannel.getChannel();
        ChannelAttrs attrs = channel.attr(VULTURE_ATTRS).get();
        if (null == attrs) {
            throwIllegalStateException("vulture channel 属性值为空");
        }
        return attrs;
    }

    /**
     * 初始化channelAttrs，该方法只适用于未被初始化过的channel
     *
     * @param vultureChannel channel
     * @return ChannelAttrs
     */
    public static ChannelAttrs init(VultureChannel vultureChannel) {
        Channel channel = vultureChannel.getChannel();
        ChannelAttrs attrs = new ChannelAttrs(vultureChannel);
        channel.attr(VULTURE_ATTRS).set(attrs);
        return attrs;
    }

    /**
     * 清理ChannelAttrs
     *
     * @param vultureChannel vultureChannel
     */
    public static void clean(VultureChannel vultureChannel) {
        Channel channel = vultureChannel.getChannel();
        channel.attr(VULTURE_ATTRS).set(null);
    }

    /**
     * 重新初始化channel
     */
    public void reInit(String accId) {
        this.recentlyEffectiveTime = System.currentTimeMillis();
        this.reuseCount++;
        this.accId = accId;
    }

    private static void throwIllegalStateException(String msg) {
        IllegalStateException e = new IllegalStateException(msg);
        log.error(msg, e);
        throw e;
    }
}
